<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <p>count:{{count}}</p>
        <button @click="increment({amount:5})">increment</button>
        <button @click="incrementAsync({amount:5})">incrementAsync</button>
    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
        Vue.use(Vuex);
        const store = new Vuex.Store({
            state:{count:0},
            mutations:{
                //mutations函数是唯一可以修改状态的地方
                //修改是同步的，不有写异步代码
                add(state,payload){
                    state.count+=payload.amount;
                }
            },
            getters:{
                doubleCount(state){
                    return state.count*2;
                }
            },
            //定义动作函数
            actions:{
                //现在可以类似于认为context就是store
                increment(context,payload){
                    console.log(context)
                    context.commit('add',payload);
                },
                incrementAsync(context,payload){
                    setTimeout(()=>{
                        context.commit('add',payload);
                    },1000);
                }
            }
        });
        var vm = new Vue({
            el:'#app',
            store,
            computed:{
                count(){
                    return this.$store.state.count;
                }
            },
            methods:{
                //把action动作映射为Vue实例的方法
                ...Vuex.mapActions(['increment','incrementAsync'])
            }
        });
        /* 
        console.log(store.state.count,store.getters.doubleCount);
        store.dispatch('increment',{amount:5});
        store.dispatch({type:'increment',amount:5});
        console.log(store.state.count,store.getters.doubleCount); */
        /**
         * context
         * state 代表仓库的状态
         * commit(type, payload, options) 用来提交mutation的方法
         * dispatch(type, payload) 用来派发action的方法
         * getters 仓库的访问器对象 类似于仓库的计算属性
         * 
         * rootGetters 根getters
         * rootState 根state 
         */
    </script>
</body>
</html>